﻿using Frame.Core.Auth;
using Frame.Core.Common.Auth;
using Frame.Core.Common.Cache;
using Frame.Core.Common.Common;
using Frame.Core.IServices.Admin;
using Frame.Core.Models;
using Frame.Core.Models.Dto;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Frame.Core.Controllers
{
    [Authorize]
    public class HomeController : BaseController
    {
        readonly IUser _user;
        readonly IPermissionHandler _permissionHandler;
        readonly ICache _cache;
        readonly IUserService _userService;
        readonly IMenuService _menuService;
        readonly IFreeSql _freeSql;
        public HomeController(IUser user, ICache cache, IOnlineService onlineService, IPermissionHandler permissionHandler, IUserService userService, IMenuService menuService, IFreeSql freeSql)
        {
            _user = user;
            _cache = cache;
            base.onlineService = onlineService;
            _permissionHandler = permissionHandler;
            _userService = userService;
            _menuService = menuService;
            _freeSql = freeSql;
        }
        #region Index
        public IActionResult Index()
        {
            //临时控制使用周期，防小人
            //var endDate = Convert.ToDateTime("2021-12-31 11:11:11");
            //string endPoint = @"http://quan.suning.com/getSysTime.do";
            //var client = new RestClient(endPoint);
            //var json = client.MakeRequest();
            //var DynamicObject = JsonConvert.DeserializeObject<dynamic>(json);
            //string sysTime2 = DynamicObject.sysTime2.ToString();
            //if (string.IsNullOrEmpty(sysTime2) || string.IsNullOrWhiteSpace(sysTime2))
            //{
            //    sysTime2 = "2021-07-06 11:11:11";
            //}
            //var webDate = Convert.ToDateTime(sysTime2);

            //if (DateTime.Compare(webDate, endDate) > 0) return Content("????????！");
            ViewBag.UserName = HttpContext.User.FindFirst(ClaimTypes.GivenName).Value;

            //获取未读消息条数
            var messageCount = 0;
            if (Convert.ToInt32(_user.TaskRoleId) == (int)BillTypeEnum.TaskRoleLaunch)//发起方，有新增权限
            {
                messageCount += _freeSql.Select<TaskScheduling>().Where(a => a.LaunchId==_user.Id && a.ResultStatus != (int)BillTypeEnum.ResultWait && a.ReadStatus == false).ToList(a => a.Id).Count;
            }
            else if (Convert.ToInt32(_user.TaskRoleId) == (int)BillTypeEnum.TaskRoleReceive)//接收方有回复权限
            {
                messageCount += _freeSql.Select<TaskScheduling>().Where(a => a.ReceiveId == _user.Id && a.ResultStatus == (int)BillTypeEnum.ResultWait).ToList(a => a.Id).Count;
            }

            ViewBag.messageCount = messageCount.ToString();
            return View();
        }

        public async Task<IActionResult> Menus()
        {
            ViewBag.UserName = HttpContext.User.FindFirst(ClaimTypes.GivenName).Value;
            // 用户可见的菜单列表
            List<Menus> menus = await ResolveUserMenuList();
            if (menus.Count == 0)
            {
                return Content("系统管理员尚未给你配置菜单！");
            }

            return Json(ToPearTree(menus));
        }

        /// <summary>
        /// 转换Pear需要的菜单
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public List<MenusDto> ToPearTree(List<Menus> list)
        {
            var dic = new Dictionary<int?, MenusDto>(list.Count);
            foreach (var chapter in list)
            {
                var menusDto = new MenusDto();
                menusDto.id = chapter.ID;
                menusDto.title = chapter.Name;
                menusDto.type = chapter.TreeLevel;
                menusDto.icon = chapter.ImageUrl;
                menusDto.href = chapter.NavigateUrl;
                menusDto.parentId = chapter.ParentID;
                dic.Add(chapter.ID, menusDto);
            }
            foreach (var chapter in dic.Values)
            {
                if (dic.ContainsKey(chapter.parentId))
                {
                    if (dic[chapter.parentId].children == null)
                        dic[chapter.parentId].children = new List<MenusDto>();
                    dic[chapter.parentId].children.Add(chapter);
                }
            }
            return dic.Values.Where(t => t.parentId == 0).ToList();
        }

        // 获取用户可用的菜单列表
        private async Task<List<Menus>> ResolveUserMenuList()
        {
            // 当前登陆用户的权限列表
            var rolePowerNames = await _userService.GetPermissionsAsync();

            // 当前用户所属角色可用的菜单列表
            List<Menus> menus = new List<Menus>();
            var menusTree = await _menuService.GetMenusAsync();
            foreach (var menu in menusTree)
            {
                // 如果此菜单不属于任何模块，或者此用户所属角色拥有对此模块的权限
                if ((menu.ViewPowerID == null || rolePowerNames.Contains(menu.Powers.Name)))
                    menus.Add(menu);
            }
            //遍历菜单，移除没有子菜单的上级菜单
            var menusNew = new List<Menus>();
            foreach (var item in menus)
            {
                var checkChild = menus.Where(p => p.ParentID == item.ID).ToList();
                if (string.IsNullOrEmpty(item.NavigateUrl))
                {
                    if (checkChild.Count != 0)
                    {
                        menusNew.Add(item);
                    }
                }
                else
                {
                    menusNew.Add(item);
                }
            }
            return menusNew;
        }

        public async Task<IActionResult> OnSignOut_Click()
        {
            //清空用户的权限列表
            var key = $"dianqi_UserPowerList_{_user.Id}";
            await _cache.DelAsync(key);
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("Login", "Login");
        }


        #endregion

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<JsonResult> CheckPassword(string password)//验证解锁密码
        {
            // 检查当前密码是否正确
            Users user = await _userService.GetAsync(a => a.ID == _user.Id);
            if (user != null)
            {
                if (!PasswordUtil.ComparePasswords(user.Password, password))
                {
                    return Json(new AjaxResult { codeIndex = 0, msg = "解锁密码不正确！" });
                }
                else
                {
                    return Json(new AjaxResult { codeIndex = 1, msg = "密码不正确！" });
                }
            }
            else
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "未知错误，请联系系统管理员！" });
            }
        }

        #region 主页

        public async Task<IActionResult> Console()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> GetSaleTotalListJson()
        {
            var dynamicData = await _freeSql.Ado.ExecuteDataTableAsync("select d.name,isnull(a.count_month,0) count_month,isnull(a.TotalSale_month,0) TotalSale_month,isnull(a.TotalOutQuantity_month,0) TotalOutQuantity_month,isnull(b.count_week,0) count_week,isnull(b.TotalSale_week,0) TotalSale_week,isnull(b.TotalOutQuantity_week,0) TotalOutQuantity_week,isnull(c.count_day,0) count_day,isnull(c.TotalSale_day,0) TotalSale_day,isnull(c.TotalOutQuantity_day,0) TotalOutQuantity_day from Store d left join (select StoreId,count(*) count_month,sum(TotalSale) TotalSale_month,sum(TotalOutQuantity) TotalOutQuantity_month from Sale  where left(BillDate,8)= left(CONVERT(varchar(100), GETDATE(), 23),8) and Status=1 and BillType=301 GROUP BY StoreId) a on a.StoreId=d.id left join (select StoreId,count(*) count_week,sum(TotalSale) TotalSale_week,sum(TotalOutQuantity) TotalOutQuantity_week from Sale  where CONVERT(datetime,BillDate,101)>=DATEADD(wk, DATEDIFF(wk,0,DATEADD(dd, -1, getdate()) ), 0) and CONVERT(datetime,BillDate,101)<DATEADD(wk, DATEDIFF(wk,0,DATEADD(dd, -1, getdate()) ), 7)  and Status=1 and BillType=301 GROUP BY StoreId) b on a.StoreId=b.StoreId left join (select StoreId,count(*) count_day,sum(TotalSale) TotalSale_day,sum(TotalOutQuantity) TotalOutQuantity_day from Sale  where BillDate= CONVERT(varchar(100), GETDATE(), 23) and Status=1 and BillType=301 GROUP BY StoreId) c on a.StoreId=c.StoreId");

            if (await _permissionHandler.CheckPower("CoreSaleView"))
            {
                return Json(new LayuiTableDataAjaxResult { code = 0, msg = "", data = dynamicData });
            }
            else
            {
                return Json(new LayuiTableDataAjaxResult { code = 0, msg = "", data = null });
            }
        }

        [HttpPost]
        public IActionResult GetEntryUserListJson()
        {
            var dynamicList = new List<dynamic>();
            var objDynamic = new
            {
                RY = "注册",
                UserTypeName = "请尽快处理"
            };
            dynamicList.Add(objDynamic);

            return Json(new LayuiTableDataAjaxResult { code = 0, msg = "", data = dynamicList });
        }

        #endregion

        #region 错误页
        [AllowAnonymous]
        public IActionResult Error()
        {
            return View();
        }
        #endregion

        #region 404
        [AllowAnonymous]
        [Route("Home/Error404/{statusCode}")]
        public IActionResult Error404()
        {
            return View();
        }
        #endregion
    }
}
